import { Card, Tree, Modal, Form, Input, Select } from 'antd'
import style from './index.module.scss'
import { companyDepartment, companyDepartmentPost, sysUserSimple } from '@/api'
import { useEffect, useState } from 'react'
import TreeItem from './components/treeItem'
const { Option } = Select
export default function Departments() {
  // tree组件的hooks
  const [initDep, setInitDep] = useState([])
  const [treeRes, setTreeList] = useState([]) // tree数据
  const [headerData, setHeaderData] = useState({}) // tree 头部数据
  //模态框的hook
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [modalText, setModalText] = useState('Content of the modal')
  const [manager, setManager] = useState([]) // 员工列表
  // form 组件的hook
  const [pid, setPid] = useState('')
  const [form] = Form.useForm()
  // tree结构转换
  function changeData(arr, i) {
    return arr.filter((v) => {
      if (v.pid === i) {
        v.children = changeData(arr, v.id)
        return v
      }
    })
  }
  async function getCompany() {
    const res = await companyDepartment()
    res.data.depts[0].manager = '负责人'
    setInitDep(JSON.parse(JSON.stringify(res.data.depts)))
    setHeaderData(res.data.depts[0])
    const list = changeData(res.data.depts, '')
    setTreeList([...list])
  }
  useEffect(() => {
    // 获取组织结构数据并转化

    getCompany()
  }, [])

  // 显示模态框
  const showModal = async (id) => {
    // console.log(id)
    setPid(id)
    // 获取员工简单列表
    if (manager.length === 0) {
      const res = await sysUserSimple()
      setManager(res.data)
      console.log(res)
    }

    setVisible(true)
  }
  // 取消并关闭模态框
  const handleCancel = () => {
    console.log('Clicked cancel button')
    setVisible(false)
  }
  // 模态框点击确认时
  const handleOk = () => {
    setModalText('The modal will be closed after two seconds')
    setConfirmLoading(true)
    form.submit()
    setTimeout(() => {
      setVisible(false)
      setConfirmLoading(false)
    }, 2000)
  }
  // 表单校验成功,发送请求
  const onFinish = async (values) => {
    console.log('Success:', values)
    const res = await companyDepartmentPost({ ...values, pid })
    getCompany()
    console.log(res)
  }

  return (
    <div className={style.departments}>
      <Card title="组织架构">
        <TreeItem showModal={showModal} data={headerData}></TreeItem>
        <hr />
        <Tree
          fieldNames={{ title: 'name', key: 'id' }}
          treeData={treeRes}
          titleRender={(node) => {
            return <TreeItem showModal={showModal} data={node}></TreeItem>
          }}
        ></Tree>
      </Card>
      <Modal
        title="新增部门"
        visible={visible}
        showModal={showModal}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 18 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          onFinish={onFinish}
        >
          <Form.Item
            label="部门名称"
            name="name"
            rules={[
              { required: true, message: '必填!' },
              { min: 2, max: 6, message: '长度需要大于2小于6' },
              {
                validator: (rule, value) => {
                  // console.log(value)
                  let res = initDep
                    .filter((v) => v.pid === pid)
                    .some((v) => v.name === value?.trim())
                  if (res) {
                    return Promise.reject(new Error('部门名重复'))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="部门编码"
            name="code"
            rules={[
              { required: true, message: '必填!' },
              {
                validator: (_, value) => {
                  let res = initDep.some((v) => v.code === value?.trim())
                  if (res) {
                    return Promise.reject(new Error('部门编码重复'))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="部门负责人"
            name="manager"
            rules={[{ required: true, message: '必填!' }]}
          >
            <Select placeholder="请选择负责人" style={{ width: 150 }}>
              {manager.map((v) => {
                return (
                  <Option key={v.id} value={v.username}>
                    {v.username}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="部门介绍"
            name="introduce"
            rules={[{ required: true, message: '必填!' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
